package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

// 用户结构体
type User struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// 验证请求结构体
type AuthRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// 验证响应结构体
type AuthResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

// 预定义的有效用户
var validUsers = map[string]string{
	"test": "pass123",
	"sj":   "readCarefully",
}

// 验证处理函数
func authHandler(w http.ResponseWriter, r *http.Request) {
	// 设置响应头
	w.Header().Set("Content-Type", "application/json")

	// 只接受POST请求
	if r.Method != http.MethodPost {
		response := AuthResponse{
			Success: false,
			Message: "只接受POST请求",
		}
		json.NewEncoder(w).Encode(response)
		return
	}

	// 解析请求体
	var req AuthRequest
	err := json.NewDecoder(r.Body).Decode(&req)
	if err != nil {
		response := AuthResponse{
			Success: false,
			Message: "无效的请求格式",
		}
		json.NewEncoder(w).Encode(response)
		return
	}

	// 验证用户名和密码
	correctPassword, exists := validUsers[req.Username]
	if !exists {
		response := AuthResponse{
			Success: false,
			Message: "❌ 用户名或密码错误",
		}
		json.NewEncoder(w).Encode(response)
		return
	}

	if correctPassword != req.Password {
		response := AuthResponse{
			Success: false,
			Message: "❌ 用户名或密码错误",
		}
		json.NewEncoder(w).Encode(response)
		return
	}

	// 验证成功
	response := AuthResponse{
		Success: true,
		Message: "🎉 登录成功",
	}
	json.NewEncoder(w).Encode(response)
}

func main() {
	// 设置路由
	http.HandleFunc("/auth", authHandler)

	// 启动服务器
	fmt.Println("服务器正在监听端口 8080...")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Printf("启动服务器失败: %v\n", err)
	}
}
